import { message } from 'antd';
import { debounce } from 'lodash';
import React, { useState, useEffect, useMemo, useCallback } from 'react';

import orchestrationService from '@/api/services/orchestrationService';
import { Empty, Button, Search } from '@/components/eai-design';
import GradientBox from '@/components/GradientBox';
import { SvgIcon } from '@/components/icon';
import Modals from '@/components/modals/Modals';
import TipsModals from '@/components/modals/TipsModals';

interface RoleTemplate {
  createTime: string;
  description: string;
  id: string;
  name: string;
  promptText: string;
  type: string;
}

// 父组件期望的模板格式
interface TemplateSelection {
  key: string;
  label: string;
  roleDescription: string;
  taskDescription: string;
}

interface RoleTemplateModalProps {
  visible: boolean;
  onClose: () => void;
  onSelect: (template: TemplateSelection, action: 'replace' | 'append') => void;
  currentRoleValue?: string; // 当前角色说明的值
  currentTaskValue?: string; // 当前任务的值
}

/** 角色模板模态框组件title * */
function TemplatesModalsHeader() {
  return (
    <div className="flex items-center">
      <SvgIcon icon="warning" size={20} color="#F08332" />
      <div className="ml-[10px] font-semibold  text-text-5">当前位置已有内容</div>
    </div>
  );
}

const RoleTemplateModal: React.FC<RoleTemplateModalProps> = function RoleTemplateModal({
  visible,
  onClose,
  onSelect,
  currentRoleValue = '',
  currentTaskValue = '',
}) {
  const [searchValue, setSearchValue] = useState('');
  const [debouncedSearchValue, setDebouncedSearchValue] = useState('');
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  const [selectedTemplate, setSelectedTemplate] = useState<RoleTemplate | null>(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [templates, setTemplates] = useState<RoleTemplate[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);

  // 防抖搜索
  const debouncedSearch = useMemo(
    () =>
      debounce((value: string) => {
        setDebouncedSearchValue(value);
      }, 300),
    [setDebouncedSearchValue],
  );

  // 处理搜索输入变化
  const handleSearchChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const { value } = e.target;
      setSearchValue(value);
      debouncedSearch(value);

      // 记录搜索历史
      if (value.trim() && !searchHistory.includes(value.trim())) {
        setSearchHistory((prev) => [value.trim(), ...prev.slice(0, 4)]); // 保留最近5个搜索
      }
    },
    [debouncedSearch, searchHistory],
  );

  // 解析MD文档格式的模板数据

  // 解析 promptText 中的角色和任务信息
  const parsePromptText = (promptText: string) => {
    let roleDescription = '';
    let taskDescription = '';

    // 提取角色部分
    const roleMatch = promptText.match(/## 角色\s*([\s\S]*?)(?=##|$)/);
    if (roleMatch) {
      roleDescription = roleMatch[1].trim();
    }

    // 提取任务部分
    const taskMatch = promptText.match(/## 任务\s*([\s\S]*?)(?=##|$)/);
    if (taskMatch) {
      taskDescription = taskMatch[1].trim();
    }

    return {
      roleDescription,
      taskDescription,
      roleDescriptionHtml: roleDescription.replace(/\n/g, '<br/>'),
      taskDescriptionHtml: taskDescription.replace(/\n/g, '<br/>'),
    };
  };

  // 获取角色模板数据
  const fetchRoleTemplates = async (page = 1, isLoadMore = false, searchText = '') => {
    if (isLoadMore) {
      setLoadingMore(true);
    } else {
      setLoading(true);
      setCurrentPage(1);
      setHasMore(true);
    }

    try {
      // 调用真实的API
      const res = await orchestrationService.getTemplateList({
        page,
        pageSize: 20,
        searchText: searchText.trim(),
      });

      // 处理后端返回的数据
      if (res && res.list && Array.isArray(res.list)) {
        if (isLoadMore) {
          // 加载更多：拼接数据
          setTemplates((prevTemplates) => [...prevTemplates, ...res.list]);
        } else {
          // 首次加载：替换数据
          setTemplates(res.list);
        }

        // 更新分页状态
        setCurrentPage(page);

        // 判断是否还有更多数据
        if (res.list.length < 20) {
          setHasMore(false);
        }

        // 如果返回的数据为空且是加载更多，说明没有更多数据了
        if (isLoadMore && res.list.length === 0) {
          setHasMore(false);
        }
      } else {
        if (!isLoadMore) {
          setTemplates([]);
          message.warning('暂无可用模板');
        }
        setHasMore(false);
      }
    } catch (error) {
      console.error('获取角色模板失败:', error);
      if (!isLoadMore) {
        message.error('获取角色模板失败');
        setTemplates([]);
      } else {
        message.error('加载更多失败');
      }
      setHasMore(false);
    } finally {
      setLoading(false);
      setLoadingMore(false);
    }
  };

  // 加载更多数据
  const loadMoreTemplates = () => {
    if (!loadingMore && hasMore) {
      fetchRoleTemplates(currentPage + 1, true, debouncedSearchValue);
    }
  };

  // 滚动监听处理
  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
    // 当滚动到距离底部50px时触发加载更多
    if (scrollHeight - scrollTop - clientHeight <= 50 && hasMore && !loadingMore) {
      loadMoreTemplates();
    }
  };

  // 组件加载时重置搜索状态
  useEffect(() => {
    if (visible) {
      // 重置搜索状态
      setSearchValue('');
      setDebouncedSearchValue('');
    }
  }, [visible]);

  // 监听搜索值变化，触发后端搜索
  useEffect(() => {
    if (visible) {
      // 搜索时重置页码到第一页
      setCurrentPage(1);
      setHasMore(true);
      fetchRoleTemplates(1, false, debouncedSearchValue);
    }
  }, [debouncedSearchValue, visible]);

  // 清理防抖函数
  useEffect(() => {
    return () => {
      debouncedSearch.cancel();
    };
  }, [debouncedSearch]);

  // 监听搜索值变化，实时更新防抖搜索
  useEffect(() => {
    if (searchValue === '') {
      setDebouncedSearchValue('');
      debouncedSearch.cancel();
    }
  }, [searchValue, debouncedSearch]);

  // 由于搜索改为后端处理，这里直接返回模板列表
  const filteredAndSortedTemplates = useMemo(() => {
    return templates.map((template) => ({ template, score: 0, matches: [] }));
  }, [templates]);

  const handleTemplateClick = (template: RoleTemplate) => {
    setSelectedTemplate(template);
  };

  const handleConfirm = () => {
    if (selectedTemplate) {
      // 检查是否存在现有内容
      const hasExistingContent = currentRoleValue.trim() || currentTaskValue.trim();

      if (hasExistingContent) {
        // 显示二次确认弹窗
        setShowConfirmModal(true);
      } else {
        // 直接应用模板
        const { roleDescription, taskDescription } = parsePromptText(
          selectedTemplate.promptText || '',
        );
        onSelect(
          {
            key: selectedTemplate.id,
            label: selectedTemplate.name,
            roleDescription: roleDescription || selectedTemplate.description || '暂无角色说明',
            taskDescription: taskDescription || '暂无任务说明',
          } as TemplateSelection,
          'replace',
        );
        handleClose();
      }
    }
  };

  const handleSecondaryConfirm = (action: 'replace' | 'append') => {
    if (selectedTemplate) {
      const { roleDescription, taskDescription } = parsePromptText(
        selectedTemplate.promptText || '',
      );
      onSelect(
        {
          key: selectedTemplate.id,
          label: selectedTemplate.name,
          roleDescription: roleDescription || selectedTemplate.description || '暂无角色说明', // 使用纯文本版本，保留原始换行符
          taskDescription: taskDescription || '暂无任务说明', // 使用纯文本版本，保留原始换行符
        } as TemplateSelection,
        action,
      );
      setShowConfirmModal(false);
      handleClose();
    }
  };

  const handleClose = () => {
    onClose();
    setSelectedTemplate(null);
    setSearchValue('');
    setShowConfirmModal(false);
  };

  const handleCancelSecondary = () => {
    setShowConfirmModal(false);
  };

  return (
    <>
      {/* 主模态窗口 */}
      <Modals
        height={640}
        title="模板选择"
        className="!font-normal"
        modelContentClassName="!p-4 !mr-0 "
        open={visible && !showConfirmModal}
        onCancel={handleClose}
        width={1065}
        footer={
          <div className="mr-2 flex justify-end gap-[30px] p-4">
            <Button
              className="w-[100px] border !border-[var(--text-2)] text-text-5"
              onClick={handleClose}
            >
              取消
            </Button>
            <Button
              type="primary"
              onClick={handleConfirm}
              disabled={!selectedTemplate}
              loading={loading}
            >
              插入提示器
            </Button>
          </div>
        }
      >
        <div className="flex">
          {/* 左侧模板列表 */}
          <div className="w-[300px]">
            <div className="mb-3">
              <Search
                placeholder="请输入内容"
                value={searchValue}
                onChange={handleSearchChange}
                allowClear
              />
            </div>

            <div className="h-[500px] overflow-y-auto " onScroll={handleScroll}>
              {loading && templates.length === 0 ? (
                <div className="py-8 text-center text-gray">
                  <div className="text-sm">加载中...</div>
                </div>
              ) : (
                <>
                  {filteredAndSortedTemplates.map(({ template }) => {
                    return (
                      <GradientBox
                        key={template.id}
                        onClick={() => handleTemplateClick(template)}
                        className="mb-2 flex h-[70px] items-center bg-fill-1 !shadow-none"
                        active={template.id === selectedTemplate?.id}
                        hover
                        bgColor="var(--bg-3)"
                      >
                        <div className="min-w-0 flex-1 p-4">
                          <div className="flex items-center">
                            <span className="text-sm font-semibold leading-[20px] text-text-5">
                              {template.name}
                            </span>
                          </div>
                          <div
                            className="mt-1 overflow-hidden text-ellipsis whitespace-nowrap text-xs text-text-3"
                            title={template.description}
                          >
                            {template.description}
                          </div>
                        </div>
                      </GradientBox>
                    );
                  })}

                  {/* 加载更多提示 */}
                  {loadingMore && (
                    <div className="py-4 text-center text-gray-500">
                      <div className="text-xs">加载更多中...</div>
                    </div>
                  )}

                  {/* 没有更多数据提示 */}
                  {!hasMore && templates.length > 0 && !loading && (
                    <div className="py-4 text-center text-gray-400">
                      <div className="text-xs">已加载全部模板</div>
                    </div>
                  )}
                </>
              )}
              {filteredAndSortedTemplates.length === 0 && (
                <div className="py-4 text-center text-gray-400">
                  <div className="text-xs">没有搜索结果</div>
                </div>
              )}
            </div>
          </div>

          {/* 右侧详情展示 */}
          <div className="flex-1 pl-4">
            {selectedTemplate ? (
              <div className="flex flex-col">
                {/* 角色说明部分 */}
                <div className="mb-4 rounded-xl bg-fill-1">
                  <div className="bg-gray-50 flex h-[217px] flex-col rounded-lg p-4">
                    <div className="mb-2 text-[16px] font-bold text-gray-800">角色说明</div>
                    <div className="flex-1 overflow-y-auto px-4 pb-4">
                      <div
                        className="text-sm leading-relaxed text-gray-700"
                        dangerouslySetInnerHTML={{
                          __html: (() => {
                            const { roleDescriptionHtml } = parsePromptText(
                              selectedTemplate.promptText || '',
                            );
                            return (
                              roleDescriptionHtml ||
                              selectedTemplate.description ||
                              '暂无角色说明'
                            ).replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
                          })(),
                        }}
                      />
                    </div>
                  </div>
                </div>

                {/* 任务部分 */}
                <div className="rounded-xl bg-fill-1">
                  <div className="bg-gray-50 flex h-[360px] flex-col rounded-lg p-4">
                    <div className="mb-2 text-[16px] font-bold text-gray-800">任务</div>
                    <div className="flex-1 overflow-y-auto">
                      <div
                        className="text-sm leading-relaxed text-gray-700"
                        dangerouslySetInnerHTML={{
                          __html: (() => {
                            const { taskDescriptionHtml } = parsePromptText(
                              selectedTemplate.promptText || '',
                            );
                            return (taskDescriptionHtml || '暂无任务说明').replace(
                              /\*\*(.*?)\*\*/g,
                              '<strong>$1</strong>',
                            );
                          })(),
                        }}
                      />
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <div className="flex h-[600px] items-center justify-center text-gray-400">
                <div className="text-center">
                  <Empty />
                </div>
              </div>
            )}
          </div>
        </div>
      </Modals>

      {/* 二次确认弹窗 */}
      <TipsModals
        width={480}
        title={<TemplatesModalsHeader />}
        open={showConfirmModal}
        onCancel={handleCancelSecondary}
        footer={
          <div className="flex justify-end gap-[10px] p-4 ">
            <Button
              className="!bg-[var(--bg-3)] !text-sm !text-text-5"
              onClick={() => handleSecondaryConfirm('replace')}
            >
              替换现有内容
            </Button>
            <Button
              type="primary"
              className="w-[144px] !text-sm !text-text-1"
              onClick={() => handleSecondaryConfirm('append')}
            >
              在现有内容后插入
            </Button>
          </div>
        }
      >
        <div className="mb-2 text-sm leading-[22px] text-text-4">
          你可以选择替换现有内容，或在其后插入新内容。
        </div>
      </TipsModals>
    </>
  );
};

export default RoleTemplateModal;
